var ws = require('ws')

var run = require('./db.js')

var wss = new ws.Server(
	{
		port: 3005,
	},
	(err) => {
		if (err) {
			return console.log('ws启动失败')
		}
		console.log('ws 启动成功')
	}
)

var user_socket = [] //用于存用户的socket
var staff_socket = null //用于存客服的socket  因为客服单一的 所以不需要id

wss.on('connection', (socket) => {

	socket.on('message', (msg) => {
		msg = JSON.parse(msg)
		console.log('有人发送消息来，类型是' + msg.type)

		switch (msg.type) {
			// 存储用户的socket
			case 'save_user_socket':
        const index =user_socket.findIndex((v) => v.uid == msg.data.uid)

				if (index=== -1) {
					user_socket.push({
						uid: msg.data.uid,
						socket: socket,
					})
				}else{
          user_socket[index] = {
						uid: msg.data.uid,
						socket: socket,
					}
        }
				break
			// 存储员工的socket
			case 'save_staff_socket':
				staff_socket = socket
				break
			//员工给用户发送消息
			case 'staff_send_msg':
				let sql = `INSERT INTO gjc_chat (content,rec_id,sender_id,sender_type,time) VALUES ( '${msg.data.content}' ,'${msg.data.rec_id}','-9999','1','${msg.data.time}') ;`

				run(sql, (err, data) => {
					if (err) {
						return staff_socket.send(sendErr())
					}
          
          const index = user_socket.find(v=>v.uid == msg.data.rec_id)
          if (index) {
            console.log('==员工给用户发消息了===');
            index.socket.send(send('userNewMsg',msg.data))
          }
				})
				break

			case 'user_send_msg':
				let sql2 = `INSERT INTO gjc_chat (content,rec_id,sender_id,sender_type,time) VALUES ( '${msg.data.content}' ,'${msg.data.rec_id}','${msg.data.sender_id}','0','${msg.data.time}') ;`
				// let sql2 =`INSERT INTO gjc_chat (content,rec_id,sender_id,sender_type,time) VALUES ( '${msg.data.content}' ,'${msg.data.uid}','-9999','1',now()) ;`
				console.log(sql2)

				run(sql2, (err, data) => {
					if (err) {
						console.log('消息存储失败')
					}
					if (msg.data.rec_id != -9999) {
						const index = user_socket.find((v) => v.uid == msg.data.rec_id)
						if (index) {
              console.log('用户给用户发消息了');
							index.socket.send(send('userNewMsg',msg.data))
						}
						return
					}
					if (staff_socket) {
						staff_socket.send(send('usersendStaffNewMsg', msg.data))
					}
				})
				break
		}

		// console.log('有人发送消息，',msg);
		// socket.send(res(0,'收到了请求',null))
		// socket.send('1111')
	})
})

function sendErr() {
	return send('is err')
}

function send(type, data) {
	return JSON.stringify({
		type: type,
		data: data,
	})
}
